package com.itheima.service;

import cn.hutool.core.collection.CollUtil;
import com.itheima.Type.CommentType;
import com.itheima.api.CommentApi;
import com.itheima.api.UserInfoApi;
import com.itheima.domain.UserInfo;
import com.itheima.exception.BusinessException;
import com.itheima.interceptor.UserHolder;
import com.itheima.mongo.Comment;
import com.itheima.server.ErrorResult;
import com.itheima.utils.Constants;
import com.itheima.vo.CommentVo;
import com.itheima.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CommentService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发布评论
    public void saveComments(String movementId, String comment) {
        //1、获取操作用户id  UserHolder获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、构造Comment 评论类型
        Comment comment1 = new Comment();
        //动态id
        comment1.setPublishId(new ObjectId(movementId));
        //评论类型
        comment1.setCommentType(CommentType.COMMENT.getType());
        //评论内容
        comment1.setContent(comment);
        //评论人
        comment1.setUserId(userId);
        //发表时间
        comment1.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        Integer commentCount = commentApi.save(comment1);

        log.info("commentCount = " + commentCount);
    }


    //分页查询评论列表
    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        //1、调用API查询评论列表
        List<Comment> list = commentApi.findComments(movementId, CommentType.COMMENT, page, pagesize);

        //判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }

        //提取所有的用户id,调用UserInfoAPI查询用户详情 查询查询集合  查询名称字段  查询类型
        List<Long> userId = CollUtil.getFieldValues(list, "userId", Long.class);
        //查到了加入集合 没查到返回空  批量将用户信息加入集合
        Map<Long, UserInfo> map = userInfoApi.findByIds(userId, null);
        //构造vo对象
        List<CommentVo> vos = new ArrayList<>();
        //遍历每个用户信息
        for (Comment comment : list) {
            //遍历出每个评论用户
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                //将评论人与被评论的动态组合起来
                CommentVo vo = CommentVo.init(userInfo, comment);
                //加入集合 组成完成
                vos.add(vo);
            }
        }
        //构造返回值
        return new PageResult(page, pagesize, 0l, vos);
    }

    //动态点赞
    public Integer likeComment(String movementId) {
        //调用api 查询用户是否点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        if (hasComment){
            throw new BusinessException(ErrorResult.likeError());
        }
        //调用api 保存数据到Mongodb
        Comment comment=new Comment();
        //动态id
        comment.setPublishId(new ObjectId(movementId));
        //评论类型
        comment.setCommentType(CommentType.LIKE.getType());
        //用户id
        comment.setUserId(UserHolder.getUserId());
        //发表时间
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);
        //拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey=Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    //取消点赞
    public Integer dislikeComment(String movementId) {
        //调用API查询用户是否已点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LIKE);
        //如果未点赞 抛出异常
        if (!hasComment){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //调用API，删除数据，返回点赞数量
        //创建圈子交互表 查询数据
        Comment comment=new Comment();
        //写入获取的动态id
        comment.setPublishId(new ObjectId(movementId));
        //写入获取的评论类型
        comment.setCommentType(CommentType.LIKE.getType());
        //写入当前评论人
        comment.setUserId(UserHolder.getUserId());
        //写入发表时间
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.delete(comment);

        //拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    //喜欢
    public Integer loveComment(String movementId) {
        //调用 api 查询是否已点赞
        Boolean hasComment = commentApi.hasComment(movementId, UserHolder.getUserId(), CommentType.LOVE);
        //为点赞抛异常
        if (hasComment){
            throw  new BusinessException(ErrorResult.loveError());
        }
        //调用api 计入该用户数据
        Comment comment=new Comment();
        //写入获取的动态id
        comment.setPublishId(new ObjectId(movementId));
        //写入获取的评论类型
        comment.setCommentType(CommentType.LOVE.getType());
        //写入当前评论人
        comment.setUserId(UserHolder.getUserId());
        //发表时间
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.save(comment);

        //拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();

        redisTemplate.opsForHash().put(key,hashKey,"1");
        return count;
    }

    //取消喜欢
    public Integer disloveComment(String movementId) {
        //1、调用API查询用户是否已点赞
        Boolean hasComment = commentApi.hasComment(movementId,UserHolder.getUserId(),CommentType.LOVE);
        //2、如果未点赞，抛出异常
        if(!hasComment) {
            throw new BusinessException(ErrorResult.disloveError());
        }
        //3、调用API，删除数据，返回点赞数量
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getUserId());
        Integer count = commentApi.delete(comment);
        //4、拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

    //评论点赞
    public Integer commentsLike(String commentsId) {
        //调用api 查询用户是否点赞
        Boolean hasComment = commentApi.commentsThumb(commentsId, UserHolder.getUserId(), CommentType.LIKE);

        //判断是否点赞 默认是
        if (hasComment){
            throw  new BusinessException(ErrorResult.likeError());
        }

        //创建圈子交互表 查询数据
        Comment comment=new Comment();

        //写入动态评论id
        comment.setPublishId(new ObjectId(commentsId));
        //写入点赞类型
        comment.setCommentType(CommentType.LIKE.getType());
        //写入当前发布评论人
        comment.setUserId(UserHolder.getUserId());
        //发表时间
        comment.setCreated(System.currentTimeMillis());
        //评论查询点赞数量 点赞+1
        Integer count = commentApi.save1(comment);
        //拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentsId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();

        redisTemplate.opsForHash().delete(key,hashKey,"1");
        return count;
    }

    //取消评论点赞
    public Integer commentsLike2(String commentsId) {
        //调用API查询用户是否已点赞
        Boolean hasComment = commentApi.commentsThumb(commentsId, UserHolder.getUserId(), CommentType.LIKE);
        //如果未点赞 抛出异常
        if (!hasComment){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //调用API，删除数据，返回点赞数量
        //创建圈子交互表 查询数据
        Comment comment=new Comment();
        //写入获取的动态id
        comment.setPublishId(new ObjectId(commentsId));
        //写入获取的评论类型
        comment.setCommentType(CommentType.LIKE.getType());
        //写入当前评论人
        comment.setUserId(UserHolder.getUserId());
        //写入发表时间
        comment.setCreated(System.currentTimeMillis());
        Integer count = commentApi.delete2(comment);

        //拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + commentsId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key,hashKey);
        return count;
    }

}
